﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPF.Core;
using static WPF.Core.Dtos.BillModel;
using WPF.Core.Dtos;
using WPF.Core.Services;

namespace WPF.Bill.ViewModels
{
    public partial class BillViewModel: NavigateViewModel
    {
        private readonly IBillService appService;
        private readonly IDialogService dialog;

        [ObservableProperty]
        private BillModel.BillPagingInfo paging;

        [ObservableProperty]
        private ObservableCollection<BillModel> gridModelList;


        public BillViewModel(IBillService appService, IDialogService dialog)
        {
            GridModelList = new ObservableCollection<BillModel>();
            this.appService = appService;
            Paging = new BillPagingInfo()
            {
                PageNumber = 1,
                PageSize = 1,
            };
            this.dialog = dialog;
        }

        [RelayCommand]
        private void Add()
        {
            dialog.ShowDialog("CreateBillView", async callBack =>
            {
                if (callBack.Result == ButtonResult.OK)
                    await GetAllAsync();
            });
        }

        [RelayCommand]
        private void Search()
        {
            GetAllAsync();
        }

        [RelayCommand]
        private async Task Delete(BillModel model)
        {
            //删除数据库数据
            await appService.Delete(model.Id);
            var todo = GridModelList.FirstOrDefault(x => x.Id == model.Id);
            if (todo != null)
            {
                //界面数据删除
                GridModelList.Remove(todo);
            }
        }

        [RelayCommand]
        private void Edit(BillModel model)
        {
            DialogParameters param = new DialogParameters();
            param.Add("Value", model);
            dialog.ShowDialog("CreateBillView", param, async callBack =>
            {
                if (callBack.Result == ButtonResult.OK)
                {
                    await GetAllAsync();
                }
            });
        }

        [RelayCommand]
        public async Task Pageing()
        { 
            await GetAllAsync();
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        private async Task GetAllAsync()
        {
            var models = await appService.GetAll(paging);
            GridModelList.Clear();
            if (models != null)
            {
                foreach (var model in models)
                {
                    GridModelList.Add(model);
                }
            }
        }
    }
}

